package com.payment.ktb.activity.main4;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StyleRes;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.flyco.animation.BaseAnimatorSet;
import com.flyco.animation.BounceEnter.BounceTopEnter;
import com.flyco.dialog.widget.base.BottomBaseDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.payment.ktb.Interface.HttpCallbackListener;
import com.payment.ktb.R;
import com.payment.ktb.activity.BaseActivity;
import com.payment.ktb.adapter.ProfitWithdrawAdapter;
import com.payment.ktb.constants.HttpActions;
import com.payment.ktb.constants.HttpUrls;
import com.payment.ktb.model.ProfitDetailEntity;
import com.payment.ktb.model.ProfitWithdrawEntity;
import com.payment.ktb.utils.AlertDialogUtils;
import com.payment.ktb.utils.HttpUtils;
import com.payment.ktb.utils.StringUtils;
import com.payment.ktb.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by admin on 2017/12/5.
 */

public class ProfitWithdrawActivity extends BaseActivity {



    @BindView(R.id.et_profitwithdraw_residuePrice)
    EditText et_profitwithdraw_residuePrice;
    @BindView(R.id.prlv_profitwithdraw)
    PullToRefreshListView prlv_profitwithdraw;
    private int page = 0;
    private BaseAnimatorSet mBasIn = new BounceTopEnter();
    //KeyboardBottomDialog mkeyBoardBottomDialog;
    CustomDialogNoBackground mkeyBoardBottomDialog;
    PreProfitWithdrawBottomDialog mPreProfitWithdrawBottomDialog;
    private Double residuePrice;
    private String amount;
    private String rateTax;
    private String rateFree;
    private String settleReal;
    private List<ProfitWithdrawEntity> listDatas = new ArrayList<>();
    private ProfitWithdrawAdapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profitwithdraw);
        ButterKnife.bind(this);
        initTitle("分润提现");

        initData();


    }

    private void initData() {



        // 设置下拉刷新加载文本
        prlv_profitwithdraw.getLoadingLayoutProxy(true, false).setPullLabel("下拉刷新...");
        prlv_profitwithdraw.getLoadingLayoutProxy(true, false).setReleaseLabel("放开刷新...");
        prlv_profitwithdraw.getLoadingLayoutProxy(true, false).setRefreshingLabel("正在加载...");
        // 设置上拉加载文本
        prlv_profitwithdraw.getLoadingLayoutProxy(false, true).setPullLabel("上拉刷新...");
        prlv_profitwithdraw.getLoadingLayoutProxy(false, true).setReleaseLabel("放开刷新...");
        prlv_profitwithdraw.getLoadingLayoutProxy(false, true).setRefreshingLabel("正在加载...");



        prlv_profitwithdraw.setMode(PullToRefreshBase.Mode.BOTH);
        prlv_profitwithdraw.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                //下拉刷新
                pullDownToRefresh();
            }
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                pullUptoLoad();


            }
        });

        //mkeyBoardBottomDialog = new KeyboardBottomDialog(mContext);
        mkeyBoardBottomDialog = new CustomDialogNoBackground(mContext,R.style.CustomDialogNoBackground);
        Window mDialogWindow = mkeyBoardBottomDialog.getWindow();
        mDialogWindow.setGravity(Gravity.BOTTOM);
        mDialogWindow.getDecorView().setPadding(0,0,0,0);
        WindowManager.LayoutParams lp = mDialogWindow.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        mDialogWindow.setAttributes(lp);




        mPreProfitWithdrawBottomDialog = new PreProfitWithdrawBottomDialog(mContext);
        et_profitwithdraw_residuePrice.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                if (hasFocus) {
                    //mkeyBoardBottomDialog.showAnim(mBasIn).show();
                    mkeyBoardBottomDialog.show();
                    et_profitwithdraw_residuePrice.clearFocus();
                }
            }
        });

        pullDownToRefresh();
        getOrgBalance();
    }








    @OnClick({R.id.btn_profitwithdraw_withdraw})
    public void clickEvent(View view) {

        switch (view.getId()) {

            case R.id.btn_profitwithdraw_withdraw:
                if (checkAmountPass()) {

                    //0:预提现 1:提现请求
                    submitWithdrwaw ("0");

                }
                break;

        }


    }

    private void submitWithdrwaw(final String preview) {

        progressDialogUtils.showProgress();

        //构造传输参数
        Map<String, String> map = new HashMap<String,String>();
        map.put("preview",preview);
        map.put("amount",(Double.parseDouble(et_profitwithdraw_residuePrice.getText().toString()) * 100) + "" );

        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.OrgBalanceSettle, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {
                progressDialogUtils.dismissProgress();
                try {
                    JSONObject jsonObject = new JSONObject(response);

                    //0:预提现 1:提现请求
                    if (preview.equals("0")) {
                        amount = jsonObject.optString("amount");
                        rateTax = jsonObject.optString("rateTax");
                        rateFree = jsonObject.optString("rateFree");
                        settleReal = jsonObject.optString("settleReal");
                        mPreProfitWithdrawBottomDialog.showAnim(mBasIn).show();

                    }else {
                        ToastUtils.showToast("提交请求成功！");
                        pullDownToRefresh();
                        getOrgBalance();
                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                }
            }

            @Override
            public void onError(VolleyError volleyError) {
                progressDialogUtils.dismissProgress();
                AlertDialogUtils.showAlertDialog(mContext, volleyError.getMessage());
            }
        });


    }


    private void pullDownToRefresh() {

        progressDialogUtils.showProgress();
        //构造传输参数
        page = 0;
        Map<String, String> map = new HashMap<String,String>();
        map.put("limit", "20");
        map.put("page", String.valueOf(page));
        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.OrgBalanceSettleRecord, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {

                try {
                    JSONObject jsonObject = new JSONObject(response);

                    progressDialogUtils.dismissProgress();
                    prlv_profitwithdraw.onRefreshComplete();

                    listDatas.clear();

                    //data
                    listDatas = new Gson().fromJson(jsonObject.getJSONArray("records").toString(), new TypeToken<List<ProfitWithdrawEntity>>() {}.getType());
                    if (listDatas == null || listDatas.isEmpty()) {
                        listDatas = new ArrayList<ProfitWithdrawEntity>();
                        ToastUtils.showToast("没有数据！");
                    }
                    //adapter
                    adapter = new ProfitWithdrawAdapter(mContext, listDatas);
                    //bind
                    prlv_profitwithdraw.setAdapter(adapter);

                } catch (JSONException e) {
                    e.printStackTrace();
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                }

            }
            @Override
            public void onError(VolleyError volleyError) {
                progressDialogUtils.dismissProgress();
                prlv_profitwithdraw.onRefreshComplete();
                AlertDialogUtils.showAlertDialog(mContext, volleyError.getMessage());
            }
        });
    }






    private void pullUptoLoad() {

        progressDialogUtils.showProgress();
        //构造传输参数
        page = page + 1;
        Map<String, String> map = new HashMap<String,String>();
        map.put("limit", "20");
        map.put("page", String.valueOf(page));
        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.OrgBalanceSettleRecord, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {

                try {

                    JSONObject jsonObject = new JSONObject(response);

                    progressDialogUtils.dismissProgress();
                    prlv_profitwithdraw.onRefreshComplete();
                    //data
                    List<ProfitWithdrawEntity> profitWithdraws = null;
                    profitWithdraws = new Gson().fromJson(jsonObject.getJSONArray("records").toString(), new TypeToken<List<ProfitDetailEntity>>() {}.getType());

                    if (profitWithdraws != null && !profitWithdraws.isEmpty()) {
                        //adapter
                        listDatas.addAll(profitWithdraws);
                        adapter.notifyDataSetChanged();
                    }else {
                        ToastUtils.showToast("没有更多数据啦！");
                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                }

            }
            @Override
            public void onError(VolleyError volleyError) {
                progressDialogUtils.dismissProgress();
                prlv_profitwithdraw.onRefreshComplete();
                AlertDialogUtils.showAlertDialog(mContext, volleyError.getMessage());
            }
        });

    }



    //代理商余额信息
    public void getOrgBalance() {

        progressDialogUtils.showProgress();

        //构造传输参数
        Map<String, String> map = new HashMap<String,String>();
        map.put("timestamp",String.valueOf(new Date().getTime()));

        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.OrgBalance, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {
                progressDialogUtils.dismissProgress();
                try {
                    JSONObject jsonObject = new JSONObject(response);

                    residuePrice = jsonObject.optDouble("residuePrice");
                    et_profitwithdraw_residuePrice.setText("可提现金额 ¥" + StringUtils.handleFen2Yuan(String.valueOf(residuePrice)));

                } catch (JSONException e) {
                    e.printStackTrace();
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                }
            }

            @Override
            public void onError(VolleyError volleyError) {
                progressDialogUtils.dismissProgress();
                AlertDialogUtils.showAlertDialog(mContext, volleyError.getMessage());
            }
        });
    }






    class PreProfitWithdrawBottomDialog extends BottomBaseDialog<PreProfitWithdrawBottomDialog> {


        @BindView(R.id.rl_prewithdraw_delete)
        RelativeLayout rl_prewithdraw_delete;
        @BindView(R.id.tv_preprofitwithdraw_amount)
        TextView tv_preprofitwithdraw_amount;
        @BindView(R.id.tv_preprofitwithdraw_rateTax)
        TextView tv_preprofitwithdraw_rateTax;
        @BindView(R.id.tv_preprofitwithdraw_rateFree)
        TextView tv_preprofitwithdraw_rateFree;
        @BindView(R.id.tv_preprofitwithdraw_settleReal)
        TextView tv_preprofitwithdraw_settleReal;
        @BindView(R.id.btn_preprofitwithdraw_cancel)
        Button btn_preprofitwithdraw_cancel;
        @BindView(R.id.btn_preprofitwithdraw_confirm)
        Button btn_preprofitwithdraw_confirm;


        public PreProfitWithdrawBottomDialog(Context context) {
            super(context);
        }

        @Override
        public View onCreateView() {
            View inflate = View.inflate(mContext, R.layout.dialog_preprofitwithdraw, null);
            ButterKnife.bind(this, inflate);
            return inflate;
        }

        @Override
        public void setUiBeforShow() {
            rl_prewithdraw_delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mPreProfitWithdrawBottomDialog.dismiss();
                }
            });

            btn_preprofitwithdraw_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mPreProfitWithdrawBottomDialog.dismiss();
                }
            });

            btn_preprofitwithdraw_confirm.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //0:预提现 1:提现请求
                    if (checkAmountPass()) {
                        mPreProfitWithdrawBottomDialog.dismiss();
                        submitWithdrwaw("1");
                    }
                }
            });

            tv_preprofitwithdraw_amount.setText("¥" + StringUtils.handleFen2Yuan(amount));
            tv_preprofitwithdraw_rateTax.setText("¥" + StringUtils.handleFen2Yuan(rateTax));
            tv_preprofitwithdraw_rateFree.setText("¥" + StringUtils.handleFen2Yuan(rateFree));
            tv_preprofitwithdraw_settleReal.setText("¥" + StringUtils.handleFen2Yuan(settleReal));
        }
    }




    private void handleMoney(String amount) {
        String temp = et_profitwithdraw_residuePrice.getText().toString().trim();
        if (temp.contains("可") || temp.equals("0")){
            et_profitwithdraw_residuePrice.setText(amount);
        }else if (temp.contains(".")) {
            if ((temp.length() - temp.indexOf(".")) <= 2)
            et_profitwithdraw_residuePrice.setText(temp + amount);
        }else {
            et_profitwithdraw_residuePrice.setText(temp + amount);
        }

    }

    private boolean checkAmountPass() {

        try {
            if (TextUtils.isEmpty(et_profitwithdraw_residuePrice.getText().toString())) {
                ToastUtils.showToast("请输入金额！");
                return false;
            }else if (Double.valueOf(et_profitwithdraw_residuePrice.getText().toString()) < 5) {
                ToastUtils.showToast("提现金额不小于5元");
                return false;
            }else if (Double.valueOf(et_profitwithdraw_residuePrice.getText().toString()) > (Double.valueOf(StringUtils.handleFen2Yuan(String.valueOf(residuePrice))))) {
                ToastUtils.showToast("可提现金额 ¥" + StringUtils.handleFen2Yuan(String.valueOf(residuePrice)));
                return false;
            }else if (Double.valueOf(et_profitwithdraw_residuePrice.getText().toString()) > 30000) {
                ToastUtils.showToast("提现金额不超过30000元");
                return false;
            }
            return true;
        }catch (Exception e) {
            ToastUtils.showToast("请输入正确的金额");
            return false;
        }

    }












    class CustomDialogNoBackground extends Dialog {

        public CustomDialogNoBackground(@NonNull Context context) {
            super(context);
        }

        public CustomDialogNoBackground(@NonNull Context context, @StyleRes int themeResId) {
            super(context, themeResId);
        }

        protected CustomDialogNoBackground(@NonNull Context context, boolean cancelable, @Nullable OnCancelListener cancelListener) {
            super(context, cancelable, cancelListener);
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.dialog_keyboard);

            Button btn_keyboard_confirm = (Button) findViewById(R.id.btn_keyboard_confirm);
            btn_keyboard_confirm.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mkeyBoardBottomDialog.dismiss();
                }
            });


            Button btn_keyboard_one = (Button) findViewById(R.id.btn_keyboard_one);
            btn_keyboard_one.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    handleMoney("1");
                }
            });

            Button btn_keyboard_two = (Button) findViewById(R.id.btn_keyboard_two);
            btn_keyboard_two.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    handleMoney("2");
                }
            });

            Button btn_keyboard_three = (Button) findViewById(R.id.btn_keyboard_three);
            btn_keyboard_three.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    handleMoney("3");
                }
            });

            Button btn_keyboard_four = (Button) findViewById(R.id.btn_keyboard_four);
            btn_keyboard_four.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    handleMoney("4");
                }
            });


            Button btn_keyboard_five = (Button) findViewById(R.id.btn_keyboard_five);
            btn_keyboard_five.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    handleMoney("5");
                }
            });

            Button btn_keyboard_six = (Button) findViewById(R.id.btn_keyboard_six);
            btn_keyboard_six.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    handleMoney("6");
                }
            });

            Button btn_keyboard_seven = (Button) findViewById(R.id.btn_keyboard_seven);
            btn_keyboard_seven.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    handleMoney("7");
                }
            });


            Button btn_keyboard_eight = (Button) findViewById(R.id.btn_keyboard_eight);
            btn_keyboard_eight.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    handleMoney("8");
                }
            });


            Button btn_keyboard_nine = (Button) findViewById(R.id.btn_keyboard_nine);
            btn_keyboard_nine.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    handleMoney("9");
                }
            });

            Button btn_keyboard_zero = (Button) findViewById(R.id.btn_keyboard_zero);
            btn_keyboard_zero.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    handleMoney("0");
                }
            });



            Button btn_keyboard_dot = (Button) findViewById(R.id.btn_keyboard_dot);
            btn_keyboard_dot.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    String temp = et_profitwithdraw_residuePrice.getText().toString();
                    if (!temp.contains("可") && !temp.contains(".") && !temp.equals("0")) {
                        et_profitwithdraw_residuePrice.setText(temp + ".");
                    }
                }
            });


            Button btn_keyboard_clear = (Button) findViewById(R.id.btn_keyboard_clear);
            btn_keyboard_clear.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    et_profitwithdraw_residuePrice.setText("可提现金额 ¥" + StringUtils.handleFen2Yuan(String.valueOf(residuePrice)));
                }
            });

            RelativeLayout rl_keyboard_deleteone = (RelativeLayout) findViewById(R.id.rl_keyboard_deleteone);
            rl_keyboard_deleteone.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    String temp = et_profitwithdraw_residuePrice.getText().toString();
                    if (!temp.contains("可")) {

                        if (temp.length() == 1) {
                            et_profitwithdraw_residuePrice.setText("可提现金额 ¥" + StringUtils.handleFen2Yuan(String.valueOf(residuePrice)));
                        }else {
                            et_profitwithdraw_residuePrice.setText(temp.substring(0,temp.length() - 1));
                        }

                    }
                }
            });




        }
    }




}
